var express = require('express');
var app = express();
var log4js = require('log4js');
log4js.configure('./config/log4js.json');
var fs = require('fs');
var path = require('path');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));

// 根据请求读取指定的路由文件
fs.readdirSync(path.join(__dirname, 'routes')).reverse().forEach(file => {
    const filename = file.replace(/\.js$/, '');
    app.use(`/${filename}`, (req, res, next) => {
        const callback = require(`./routes/${filename}`);
        // 允许跨域
        res.header("Access-Control-Allow-Origin","*");
        res.header("Access-Control-Allow-Methods","POST,GET");
        callback(req, res, next);
    });  
})


app.set('port', process.env.PORT || 5000);

var server = app.listen(app.get('port'), function() {
    console.log(`This app is running in ${app.get('port')} port`);
    log4js.getLogger("startup").info('Express server listening on port ', server.address().port, " with pid ", process.pid );
});